import {execScript} from "./tools";

const PluginManager = {
    initialized: false,
    _pluginInterfaces: [],
    _plugins: [],
    _manifests: [],
    exec: async function () {
        if (!PluginManager.initialized) {
            console.log("Waiting for initialization");
            setTimeout(PluginManager.exec, 1);
        } else {

            var checkRule = async (pattern) => {
                return currentTab().then(tab => {
                    console.log(tab.url);
                    return pattern.test(tab.url);
                })
                return pattern.test();
            }
            var execPlugin = ({class_name: cn, matches: matches, js: js}) => {
                console.log(cn, matches, js);
                chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
                    console.log(tabs[0].id);
                    execScript(tabs[0].id, script);
                });
            }
            PluginManager._plugins.forEach(execPlugin)
        }
    },

    init: async function () {
        var readFile = async function (file) {
            var content = "";
            var url = chrome.runtime.getURL(file);
            try {
                content = await fetch(url).then(function (response) {
                    if (response.ok && response.status === 200) {
                        return response.text();
                    } else throw new Error(`status: ${response.status}`);
                }).catch(function (err) {
                    console.log(err);
                    return ""
                })
            } catch (e) {
                console.log("getRawContent " + e);
            }
            return content;
        };
        var loadManifest = async function (file) {
            return readFile(file)
                .then(res => JSON.parse(res))
                .catch((err) => {
                    console.log("loadManifest error", err);
                    return null;
                });
        }
        var manifest = await loadManifest("assets/plugins/manifest.json");
        PluginManager._manifests = manifest.manifests;
        PluginManager._pluginInterfaces.push(...manifest.plugins);
        for (var file of manifest.manifests) {
            await loadManifest(file).then(res => {
                for (var a in res.plugins) {
                    for (var b in res.plugins[a].js) {
                        res.plugins[a].js[b] = chrome.runtime.getURL(res.plugins[a].js[b]);
                    }
                }
                PluginManager._plugins.push(...res.plugins);
            });
        }
        PluginManager.initialized = true;
        // console.log(plugins);
    }
};
export {PluginManager};